import React, { useState, useMemo } from "react"
import { Divider } from "antd"

type ExpensiveComponentProps = {
  items: number[]
}

const UseMemoExpensiveComponent: React.FC<ExpensiveComponentProps> = ({
  items,
}) => {
  const sortedItems = useMemo(() => {
    console.log("sortedItems from UseMemoExpensiveComponent")
    return [...items].sort((a, b) => a - b)
  }, [items])

  //   const sortedItems = [...items].sort((a, b) => a - b)
  //   console.log("sortedItems", sortedItems)

  return (
    <div>
      <h3>Sorted Items:</h3>
      <ul>
        {sortedItems.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  )
}

const NotUseMemoExpensiveComponent: React.FC<ExpensiveComponentProps> = ({
  items,
}) => {
  const sortedItems = () => {
    console.log("sortedItems from NotUseMemoExpensiveComponent")
    return [...items].sort((a, b) => a - b)
  }

  const a = sortedItems()

  return (
    <div>
      <h3>Sorted Items:</h3>
      <ul>
        {a.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  )
}

const UseMemoPage: React.FC = () => {
  const [count, setCount] = useState<number>(0)
  const [items] = useState<number[]>([10, 20, 30, 40, 50])

  return (
    <div>
      <h1>UseMemoPage</h1>
      <h6>see console to understand the difference</h6>

      <button onClick={() => setCount(count + 1)}>
        Increment Count: {count}
      </button>
      <Divider />
      <h2>useMemo Demo</h2>
      <UseMemoExpensiveComponent items={items} />
      <Divider />
      <h2>not useMemo Demo</h2>
      <NotUseMemoExpensiveComponent items={items} />
    </div>
  )
}

export default UseMemoPage
